#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from os import path, access, environ, urandom, R_OK, mkdir
from hashlib import sha512
from sys import argv, exit, stderr, stdout
from base64 import b64encode

PATH = path.join(path.expanduser('~'), '.urlpassgen', 'salt')


def salt_gen(salt_file):
    stderr.write('Prepare salt file\n')

    if not path.isdir(path.dirname(PATH)):
        mkdir(path.dirname(PATH))

    # prepare salt
    temp = sha512(urandom(512))
    for i in ['version', 'cpuinfo', 'devices', 'cmdline',
        'modules', 'mounts', 'swaps', 'partitions']:
        f = '/proc/%s' % i
        if path.isfile(f) and access(f, R_OK):
            temp.update(i + open(f, 'rb').read())

    temp.update(str(environ))

    salt = temp.digest()
    del temp

    with open(salt_file, 'wb') as f:
        f.write(salt)
    return True


def pass_gen(url, passwd, hex=False):
    if not path.isfile(PATH):
        salt_gen(PATH)

    stderr.write('Find salt file\n')
    with open(PATH, 'rb') as f:
        tmp = sha512(f.read())

    tmp.update(url)
    tmp.update(passwd)

    return tmp.digest().encode('hex') if hex else b64encode(tmp.digest(), "-*")


if __name__ == "__main__":
    if len(argv) < 3:
        stderr.write('''Have no params. USE:
   %s URL PASSWORD
''' % path.basename(argv[0]))
        exit(1)

    stderr.write('PASSWORD:\n')
    stdout.write(pass_gen(argv[1], argv[2]) + '\n')

